package com.tica.it.itmanage.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tica.catool.common.Result;
import com.tica.it.itmanage.config.jwt.JwtUtil;
import com.tica.it.itmanage.core.domain.security.UserEntity;
import com.tica.it.itmanage.core.dto.LoginDTO;
import com.tica.it.itmanage.core.dto.UserDetailDTO;
import com.tica.it.itmanage.server.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 *
 */
@Api(tags = "登陆管理")
@Slf4j
@RestController
public class LoginController {

    @Autowired
    UserService userService;

//    @ApiOperation(value = "获取token")
//    @PostMapping("/getToken")
//    public Result<String> getToken(@RequestBody UserDTO user) {
//
//        UserDetailDTO userDetail = new UserDetailDTO();
//
//        String token = JwtUtil.sign(userDetail);
//        return Result.ok(token);
//    }

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public Result<String> login(@RequestBody @Valid LoginDTO userLoginDTO, HttpServletResponse response) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, userLoginDTO.getUsername()));
        if (user == null) {
            return Result.fail(10001, "用户名不存在");
        }

        if (!user.getPassword().equals(password)) {
            return Result.fail(10002, "用户名或密码错误");
        }
        UserDetailDTO userDetail = new UserDetailDTO();
        userDetail.setUsername(username);
        String token = JwtUtil.sign(userDetail);
        return Result.ok(token);
    }




    @PostMapping("/test")
    public Result<String> test() {
        System.out.println("进入测试，只有带有令牌才可以进入该方法");
        return Result.ok();
    }


}
